package com.wing.user.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.user.dao.MenuDao;
import com.wing.user.model.entity.Menu;
import com.wing.user.model.entity.RoleMenu;
import com.wing.user.model.response.MenuVO;
import com.wing.user.utils.Constant;
import com.wing.user.model.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单-ServiceImpl
 *
 * @author
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuDao, Menu> implements MenuService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public void setValue(Menu menu) {
        if (menu == null) {
            return;
        }
        Menu parent = null;
        if (menu.getParentId() != null && menu.getParentId() != -1) {
            parent = baseMapper.selectById(menu.getParentId());
        }
        if (parent != null) {
            menu.setTreePath(parent.getTreePath() + parent.getId() + Constant.TREE_PATH_SEPARATOR);
        } else {
            menu.setTreePath(Constant.TREE_PATH_SEPARATOR);
        }
        String[] parentIds = StringUtils.split(menu.getTreePath(), Constant.TREE_PATH_SEPARATOR);
        menu.setGrade(parentIds.length - 2);
    }

    @Override
    public List<MenuVO> listAllAndButton() {
        return this.baseMapper.listAllAndButton();
    }

    @Override
    public List<MenuVO> listAllMenuAndButton(Long roleId) {
        return this.baseMapper.listAllMenuAndButton(roleId);
    }

    @Override
    public List<MenuVO> listByUserId(Long userId) {
        List<Role> roleList = userRoleService.listByUserId(userId);
        List<Long> idList = new ArrayList<>();
        for(Role role : roleList){
            idList.add(role.getId());
        }
        return listByRoleIds(idList);
    }

    @Override
    public List<MenuVO> listByRoleIds(List<Long> roleIds) {
        if (roleIds == null || roleIds.size() == 0) {
            return new ArrayList<>();
        }
        return baseMapper.listByRoleIds(roleIds);
    }

    @Override
    public List<MenuVO> listByRoleId(Long roleId) {
        List<Long> roleIds = new ArrayList<>();
        if (roleId != null) {
            roleIds.add(roleId);
        }
        return listByRoleIds(roleIds);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        this.removeById(id);
        roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("menu_id", id));
    }

    @Override
    public MenuVO getMenuByUrl() {
        return baseMapper.getMenuByUrl();
    }
}
